package com.ahncnk.powermonitor.admin.devices.service;

import com.ahncnk.powermonitor.admin.devices.domain.entity.Device;
import com.ahncnk.powermonitor.admin.devices.domain.projection.GeoDevice;
import com.ahncnk.powermonitor.admin.devices.repository.DeviceRepository;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * DeviceService
 *
 * @author lipei
 */
@Service
public class DeviceService {
    @Resource
    private DeviceRepository deviceRepository;

    public Page<Device> search(@Nullable String name, @Nullable String sn, @Nullable Boolean offline, Pageable pageable) {
        Device query = new Device();
        query.setName(name);
        query.setSn(sn);
        query.setOffline(offline);

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());

        Example<Device> example = Example.of(query, matcher);
        return deviceRepository.findAll(example, pageable);
    }

    public Iterable<GeoDevice> listGeoDevices(String district) {
        return deviceRepository.findGeoDevicesByDistrict(district);
    }
}
